(function(){
  nsbase.views.dashbord = new DashbordFunc();

  
  function DashbordFunc () {
    var _self = this;

    _self.init = init;

    var dashboardActions = nsbase.config.actionUrl.dashboard,
        utilities = nsbase.utility,
        clientResource = nsbase.resources.clientResource;
    var cssClass={
      selected:"selected"
    };
    var $leftContainer = $(".perf_total .left"),
        $rightContainer = $(".perf_total .right"),
        $btnClose = $(".btnClose"),
        $contentItem = $(".item_content li"),
        $chartItem = $("#itemChart"),
        $chartContainer = $chartItem.find(".chartContainer");

    var $curKpiBox = null,$curItemBox = null;
    var _shareContent = "";

    function init () {
      $(".nav_menu li.Dashboard").addClass(cssClass.selected);
      initTotalPerf();
      initKpiBox();
      
      
      $(".item_list").arrowSlide();
    }
    function bindShareWeibo (statType) {
      var $shareContainer = $("#shareContainer"),
          $btnShare = $("#btnShare"),
          $btnSinaShare = $shareContainer.find('.sina'),
          $btnTencentShare = $shareContainer.find('.tencent');

      getShareContent(statType);
      $btnShare.unbind('click').click(function(event) {
        if($shareContainer.is(":visible")){
          $shareContainer.slideUp('400');
        } else{
          $shareContainer.slideDown('400');
        }
      });

      // sina weibo share
      $btnSinaShare.click(function(event) {
        var s = screen,d=document,e=encodeURIComponent;
        //var shareContent = $("#shareContent").text();
        var f='http://v.t.sina.com.cn/share/share.php?',
          u=d.location.href,
          p=['url=',e(u),'&title=',e(_shareContent),'&appkey=1392530042'].join('');// appkey 显示分享来源为 分享按钮
        function a(){
          if(!window.open([f,p].join(''),'mb',['toolbar=0,status=0,resizable=1,width=620,height=450,left=',(s.width-620)/2,',top=',(s.height-450)/2].join('')))
          u.href=[f,p].join('');
        };
        if(/Firefox/.test(navigator.userAgent)){
          setTimeout(a,0);
        }else{
          a();
        }
      });

      // tencent weibo share
      $btnTencentShare.click(function(event) {
        //var shareContent = $("#shareContent").text();
        var _t = encodeURI(_shareContent),
          _url = encodeURI(document.location.href),
          _appkey = '333cf198acc94876a684d043a6b48e14',// 分享来源 显示为 一键转播组件
          _site = encodeURI, 
          _pic = '';
        var _u = 'http://v.t.qq.com/share/share.php?title='+_t+'&url='+_url+'&appkey='+_appkey+'&site='+_site;
        window.open( _u,'分享到腾讯微博', 'width=620, height=450, top='+(screen.height-450)/2+', left='+(screen.width-620)/2 +', toolbar=no, menubar=no, scrollbars=no, location=yes, resizable=no, status=no' );  
      });
    }

    function getShareContent (shareType) {
      
      nsbase.ajax.request(dashboardActions.getShareInfo, null, function(result) {
          if(result.success){
            var shareInfo = result.data;
            if(shareType == "run"){
              var tmplContent = $("#runShare").text();
              _shareContent = utilities.stringFormat(tmplContent,shareInfo.runMiles,shareInfo.calorie);
            } else if (shareType){
              var tmplContent = $("#sleepShare").text();
              _shareContent = utilities.stringFormat(tmplContent,shareInfo.sleepHour,(shareInfo.sleepHour>=8?"真是人见人爱呀":"不就不美啦"));
            } else {
              _shareContent = "";
            }
          } else {
            _shareContent = "";
          }
        },function(e){
            _shareContent = "";
        });
    }

    function initTotalPerf () {
      $(".btnCalories").click(function(){
          $leftContainer.find(".perf_pic").animate({"margin-top":-315});
          var chartConfig = getCalorieChartConfig();
          bindSummaryChart(chartConfig,1);
      });

      $(".btnWeight").click(function () {
          $rightContainer.find(".perf_pic").animate({"margin-top":-315});
           var chartConfig = getDateChartConfig();
          bindSummaryChart(chartConfig,2);
      });

      $btnClose.click(function(){
          var sender = $(this);
          sender.parents("li").find(".perf_pic").animate({"margin-top":0});
      });
    }


    function initKpiBox () {

      $contentItem.click(function(){
        var sender = $(this);
        if(sender.hasClass(cssClass.selected)) return;

        $curItemBox = sender.find('.item_box');
        var statType = $curItemBox.attr("stat-type");
        if(!statType){
          $chartItem.hide();
          return;
        } 
        sender.parent("ul").find("li").removeClass(cssClass.selected);
        sender.addClass(cssClass.selected);

        $(".chart_box").hide();
        $curKpiBox = $(".chart_box."+statType);
        $curKpiBox.show();
        if(statType == "run" || statType == "sleep"){
          initKpiChartArea();
          bindShareWeibo(statType);

          $curKpiBox.find(".select_kpi ul").hide();
          $curKpiBox.find(".select_kpi ul.kpi_"+ statType).show();
          //$curKpiBox.find(".select_kpi kpi_"+ statType +" li:first").click();
          $curKpiBox.find('.select_time li[day-range="0"]').removeClass(cssClass.selected).click();
        }

        if(statType == "diagnose"){
          $curKpiBox.find(".select_kpi li").unbind('click').click(function(){
            var sender = $(this);
            if(sender.hasClass(cssClass.selected)) return;

            sender.parent("ul").find("li").removeClass(cssClass.selected);
            sender.addClass(cssClass.selected);

            if(sender.parent("ul").hasClass('kpi_diagnose')){
              $curKpiBox.find('.diag_block').css('display', 'none');;
              $curKpiBox.find('.diag_block.'+ sender.attr("stat-type")).css('display',"inline-block");
            }
          });

          bindDiagnoseBox();
        }

        if(statType == "food"){
          bindFoodBox($curKpiBox);
        }
      });

      
    }

    function bindDiagnoseBox () {
        var $diagnoseContainer = $(".diagnoseContainer"),
            $diagDescContainer = $diagnoseContainer.find('.diagnose3 .diag_desc');
        $diagnoseContainer.find("li").unbind('click').click(function() {
            var $sender = $(this);
            if($sender.hasClass(cssClass.selected)){
              return;
            }
            $diagnoseContainer.find("li").removeClass(cssClass.selected);
            $sender.addClass(cssClass.selected);
        });
        $diagnoseContainer.find(".diagnose3 li").unbind('click').click(function() {
          var $sender = $(this);
          var title = $sender.find('.item_title').text();
          var desc = $sender.find('.item_desc').text();
          title = title.substring(title.indexOf('%')+1);
          $diagDescContainer.find('.title').text(title);
          $diagDescContainer.find('.desc').text(desc);
        });

      $diagnoseContainer.find(".diagnose3 li:first").click();
    }

    function bindFoodBox ($foodBox) {
      var $leftBox = $foodBox.find(".food_list .list_left");
      var $rightBox = $foodBox.find('.food_list .list_right');
      var groupTmpl = $foodBox.find('.groupTmpl').html();

      if($leftBox.children().length > 0){
        return;
      }

      nsbase.ajax.request(dashboardActions.getFoodList, null, function(result) {
        if(result.success){
            bindFoodGroup(result.data);
        }
      },function(e){
          
      });

      function bindFoodGroup(foodGroups){
        if(!foodGroups || foodGroups.length == 0){
          return;
        }
        for (var i = 0; i < foodGroups.length; i++) {
          var foodGroup = foodGroups[i];
          if(foodGroup.type < 4){ // 酸性食物
            $leftBox.append(utilities.tmplFormat(groupTmpl,foodGroup,groupFormat))
          } else { // 碱性食物
            $rightBox.append(utilities.tmplFormat(groupTmpl,foodGroup,groupFormat))
          }
        };

        var $foodPhCur = $foodBox.find(".ph_cur");
        var foodValue = 0,sumValue = 0;
        $foodBox.find('.list_group li').click(function() {
          var $sender = $(this);
          var originalLeft = parseInt($foodPhCur.css('left'));
          var foodValue = parseInt($sender.attr("value"));
          if($sender.hasClass(cssClass.selected)){
            foodValue = -foodValue;
            $sender.removeClass(cssClass.selected);
          } else {
            $sender.addClass(cssClass.selected);

          }

          var $selectedFoods = $foodBox.find('.list_group li.selected');
          $(".foodCount").text($selectedFoods.length);
          
          $foodPhCur.animate({'left': originalLeft + foodValue*5},'slow', function() {
            
          });
          
          sumValue += foodValue;
          var $sumTitle = $foodBox.find(".sumTitle");
          if(sumValue < 0){
            $sumTitle.html('您的饮食偏<span>酸性</span> 易疲劳');
          } else if(sumValue == 0){
            $sumTitle.html('您的饮食呈<span>中性</span> 较均衡');
          } else {
            $sumTitle.html('您的饮食偏<span>碱性</span> 利美肤');
          }

        });
      }

      function groupFormat (foodGroup,dataIndex) {
        var foodsList = "";
        switch(dataIndex){
          case "foods":
            for (var i = 0; i < foodGroup.foods.length; i++) {
             var food = foodGroup.foods[i];
             var foodValue = parseInt(food.value);
             if(foodGroup.type < 4){
                foodValue = -foodValue;
             }
             foodsList += "<li value='"+ foodValue +"'>"+ food.name +"</li>"
            };
            break;
        }
        return foodsList
      }

    }

    function initKpiChartArea(){
      var $txtMinuteRange = $("#txtMinuteRange");
      var hour = new Date().getHours();
      $txtMinuteRange.val(parseInt(hour/6)*6);

      $curKpiBox.find(".select_time li").unbind("click").click(function(){
        var sender = $(this);
        if(sender.hasClass(cssClass.selected)) return;

        $curKpiBox.find(".select_time li").removeClass(cssClass.selected);
        sender.addClass(cssClass.selected);
        var dayRange = sender.attr("day-range");
        var $timeRange = $curKpiBox.find(".time_range");
        $timeRange.children("div").hide();
        $timeRange.children("div.range_"+ dayRange).show();

        if(dayRange > 1 ){ // 近多少天，出一天数据
          var startDate = utilities.dateFormat(utilities.getDate(-dayRange+1),"yyyy-MM-dd");
          var endDate = utilities.dateFormat(utilities.getDate(),"yyyy-MM-dd");
          $timeRange.children("div.range_"+ dayRange).text(utilities.stringFormat(clientResource.lblTo,startDate,endDate));
          // 绑定chart 图
          bindKpiItemChart("day",startDate,endDate);
        } else if(dayRange == 1){ // 昨天 出小时数据
          var startDate = $("#txtDatePicker").val();
          // 绑定chart 图
          bindKpiItemChart("hour",startDate);
        } else if(dayRange == 0){// 当天分钟数据
          var startHour = parseInt($txtMinuteRange.val());
          var endHour = startHour+6;
          bindKpiItemChart("minute", startHour+":00", endHour+":00");
        }
      });

      $txtMinuteRange.change(function(event) {
        var startHour = parseInt($txtMinuteRange.val());
        var endHour = startHour+6;
        bindKpiItemChart("minute", startHour+":00", endHour+":00");
      });

      $curKpiBox.find(".select_kpi li").unbind('click').click(function(){
        var sender = $(this);
        if(sender.hasClass(cssClass.selected)) return;

        sender.parent("ul").find("li").removeClass(cssClass.selected);
        sender.addClass(cssClass.selected);

        $chartContainer.show();
        $curKpiBox.find('.select_time').show();
        var dayRange = $curKpiBox.find(".select_time li.selected").attr("day-range");
        if(dayRange > 1 ){// 出天数据
          var startDate = utilities.dateFormat(utilities.getDate(-dayRange+1),"yyyy-MM-dd");
          var endDate = utilities.dateFormat(utilities.getDate(),"yyyy-MM-dd");
          // 绑定chart 图
          bindKpiItemChart("day",startDate,endDate);
        } else if(dayRange == 1){//昨天出小时数据
          var startDate = $("#txtDatePicker").val();
          // 绑定chart 图
          bindKpiItemChart("hour",startDate);
        } else if(dayRange == 0){// 今天 出分钟数据
          var startHour = parseInt($txtMinuteRange.val());
          var endHour = startHour+6;
          bindKpiItemChart("minute", startHour+":00", endHour+":00");
        } else { // 自定义出天数据
          var startDate = $("#txtStartDate").val();
          var endDate = $("#txtEndDate").val();
          bindKpiItemChart("day",startDate,endDate);
        }
      });

      $("#txtDatePicker").datepicker({
        maxDate:-1,
        dateFormat:"yy-mm-dd",
        onSelect:function(dateText,datepicker){
          // 绑定 图
          bindKpiItemChart("hour",dateText);
        }
      });
      $("#txtDatePicker").val(utilities.dateFormat(utilities.getDate(),"yyyy-MM-dd"));
      $("#txtStartDate").datepicker({
        maxDate:-1,
        defaultDate:-6,
        dateFormat:"yy-mm-dd",
        onSelect:function(dateText,datepicker){
          $("#txtEndDate").datepicker("option","minDate",dateText);
          // 绑定 图
          bindKpiItemChart("day",dateText,$("#txtEndDate").val());
        }
      });
      $("#txtStartDate").val(utilities.dateFormat(utilities.getDate(-6),"yyyy-MM-dd"));
      $("#txtEndDate").datepicker({
        maxDate:-1,
        minDate:-7,
        defaultDate:-1,
        dateFormat:"yy-mm-dd",
        onSelect:function(dateText,datepicker){
          $("#txtStartDate").datepicker("option","maxDate",dateText);
          // 绑定 图
          bindKpiItemChart("day",$("#txtStartDate").val(),dateText);
        }
      });
      $("#txtEndDate").val(utilities.dateFormat(utilities.getDate(),"yyyy-MM-dd"));
    }

    function bindKpiItemChart (timeUnit, starTime,endTime) {
      
      var kpiChartConfig = getKpiChartConfig(timeUnit);
      if(!kpiChartConfig){
        return;
      }
      var chartContainer =  kpiChartConfig.container;
      //chartContainer.show();
      chartContainer.mask();
      var param = {},url;
      if(timeUnit == "minute"){
        param = {
          startHour:starTime,
          endHour:endTime,
          statType:kpiChartConfig.statType
        };
        url = dashboardActions.getMinuteChartData;
      } else {
        param = {
          start_date:starTime,
          end_date:endTime,
          time_Unit:timeUnit,
          stat_type:kpiChartConfig.statType
        };
        url = dashboardActions.getKpiItemChartData;
      }
      nsbase.ajax.request(url, param, function(result) {
          chartContainer.unmask();
          if(result.success){
            kpiChartConfig.xAxis.series = result.data.xAxis;
            kpiChartConfig.yAxis.series = result.data.yAxis;
            createChart(kpiChartConfig);
          } else {
            chartContainer.empty();
          }
        },function(){
          chartContainer.unmask();
        });
    }

    function getKpiChartConfig (timeUnit) {
      
      var statType = $curItemBox.attr("stat-type");
      var $kpiObj = $curKpiBox.find(".select_kpi ul.kpi_"+ statType +" li.selected");
      if($kpiObj.attr("stat-type")){
        statType = $kpiObj.attr("stat-type");
      }
      if(!statType){
        return null;
      }
      var kpiTitle = $kpiObj.text();
      var kpiSuffic = "",xSuffic = "";
      switch(statType){
        case "calorie":
          kpiSuffic = clientResource.unitCal;
          break;
        case "run":
          kpiSuffic = clientResource.unitKM;
          break;
        case "jump":
          kpiSuffic = clientResource.unitNum;
          break;
        case "sleep":
          kpiSuffic = clientResource.unitHour;
        default:
          break;
      };

      switch (timeUnit){
        case "day":
          xSuffic = clientResource.unitDay;
          break;
        case "hour":
          xSuffic = clientResource.unitHour;
          break;
        case "minute":
          xSuffic = clientResource.unitMinute;
          break;
      }
      
      var chartConfig = {
          container:$chartContainer,
          chartType:"column",
          title:kpiTitle,//"卡路里VS个数"||"睡时"
          xAxis:{
            title:{
              enabled: true,
              text: clientResource.lblTime + " ("+ xSuffic +")"
            },
            series:[]
          },
          yAxis:{
            title: kpiTitle +"("+kpiSuffic+")",
            series:[]
          },
          tooltip:{
            valueSuffix: kpiSuffic
          },
          statType:statType
      };

      return chartConfig;
    }

    function bindSummaryChart (chartConfig,statType) {
      chartConfig.container.mask();
      var param = {
        start_date:utilities.dateFormat(utilities.getDate(-6),"yyyy-MM-dd"),
        end_date:utilities.dateFormat(utilities.getDate(),"yyyy-MM-dd"),
        stat_type: statType //"统计类型：1-卡路里；2-时间"
      };

      nsbase.ajax.request(dashboardActions.getSummaryChartData, param, function(result) {
          chartConfig.container.unmask();
          if(result.success){
            chartConfig.xAxis.series = result.data.xAxis;
            chartConfig.yAxis.series = result.data.yAxis;
            createChart(chartConfig);
          } else {
            utilities.errorDialog(result.message);
          }
        },function(){
          chartConfig.container.unmask();
        });
    }

    function getCalorieChartConfig () {
      var config = {
          container:$leftContainer.find('.chartContainer'),
          chartType:"column",
          title:clientResource.chartTitleTotalCal,
          //subtitle:"最近7天",
          colors:["#D2D2D2","#1CAC00"],
          xAxis:{
            series:[],
            labels:{
              rotation:-45,
              align:'right',
              formatter:function () {
                //return utilities.dateFormat(this.value,"MM-dd");
                return this.value;
              }
            }
          },
          yAxis:{
            title:utilities.stringFormat("{0}({1})",clientResource.lblCal,clientResource.unitCal),
            series:[]
          },
          tooltip:{
            valueSuffix: clientResource.unitCal
          }

      };
      return config;
    }

    function getDateChartConfig () {
      var config = {
          container:$rightContainer.find('.chartContainer'),
          chartType:"column",
          title:clientResource.chartTitleTotalSleep,
          //subtitle:"最近7天",
          colors:["#D2D2D2","#1CAC00"],
          xAxis:{
            series:[],
            labels:{
              rotation:-45,
              align:'right',
              formatter:function () {
                //return utilities.dateFormat(this.value,"MM-dd");
                return this.value;
              }
            }
          },
          yAxis:{
            title: utilities.stringFormat("{0}({1})",clientResource.lblRunTime,clientResource.unitHour),
            series:[]
          },
          tooltip:{
            valueSuffix: clientResource.unitHour
          }

      };
      return config;
    }

    function fallPictures($picture) {
      var $picture = $('<img src="../static/images/icon_coord.png" style="position:absolute;"/>');
      $("body").append($picture);
      $picture.css({"top":0,"left":0});
      $picture.animate({"top":top});
    }

    function createChart (option) {
      // var config = {
      //     container:"",
      //     chartType:"column",
      //     title:"总卡路里消耗",
      //     subtitle:"最近7天",
      //     xAxis:[],
      //     yAxis:{
      //       title:"",
      //       series:[]
      //     },
      //     tooltip:{
      //       valueSuffix: 'cal'
      //     }
      // };

      var fontColor="#6b6b6b";
      var chartOption = {
          chart: {
            type: option.chartType,
            marginTop: 60
          },
          colors:['#1CAC00','#F88614'],
          title: {
            text: option.title,
            style:{
              color:fontColor,
              fontWeight: 'bold'
            }
          },
          credits:{
            enabled: false
          },
          xAxis: {
            categories: option.xAxis.series,
            labels:{
              rotation:-45,
              step:Math.ceil(option.xAxis.series.length/10)
            },
            title:{
              enabled:option.xAxis.title?option.xAxis.title.enabled:false,
              text:option.xAxis.title?option.xAxis.title.text:"",
              style: {
                color: fontColor
              }
            }
          },
          yAxis: {
              title: {
                  text: option.yAxis.title,
                  style:{
                    color:fontColor
                  }
              },
              min:0,
              plotLines: [{
                  value: 0,
                  width: 1,
                  color: fontColor
              }]
          },
          tooltip: {
              valueSuffix: option.yAxis.valueSuffix,
              pointFormat:'<span style="color:{series.color}">{series.name}</span>: <b>{point.y:,.1f}</b>'
          
          },
          legend: {
              enabled:option.yAxis.series.length > 1,
              align: 'center',
              floating:true,
              verticalAlign: 'top',
              y: 20,
              borderWidth: 0
          },
          series: option.yAxis.series
      };
      if(option.colors){
        chartOption.colors = option.colors;
      }
      if(option.subtitle){
        chartOption.subtitle = {
          text: option.subtitle,
          style:{
            color:fontColor
          }
        };
      }
      if(option.xAxis.labels){
        chartOption.xAxis.labels = option.xAxis.labels;
      }
      
      option.container.highcharts(chartOption);
    }
  }
})();
